import Vue from 'vue'
import Vuex from "vuex"
import getters from "./getters";

Vue.use(Vuex)

const store = new Vuex.Store({
  state:{
    cartList:[],
  },
  getters,
  actions:{
    addCart(context,payload){
      return new Promise((resolve,reject)=>{
        // 查找数组内是否有相同值
        let product=context.state.cartList.find((item)=>item.iid === payload.iid)
        if(product){
          context.commit('addCount',product);
          // product.count+=1;
          resolve('当前商品数量加一');
        }else{
          context.commit('addProduce',payload);
          resolve("当前新添加了一个商品");
        }
      })
    }
  },
  mutations:{
    addCount(state,payload){
      payload.count+=1;
    },
    addProduce(state,payload){
      payload.count=1;
      // 添加属性，默认选中状态
      payload.checked=true;
      state.cartList.push(payload);
    }
  }
})

export default store

